﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public class SmartHouseEvent
    {
        private string name;
        private string description;
        private bool isActive;
        private List<Variable> sourceList;
        private ConditionSet conditionSet;

        public event EventHandler Triggered;

        public bool IsActive
        {
            get { return isActive; }
            set { isActive = value; }
        }

        public string Description
        {
            get { return description; }
            set { description = value; }
        }

        public string Name
        {
            get { return name; }
        }

        public List<Variable> variables     // Vanya Edit start  
        {
            get { return sourceList; }
            set 
            { 
                sourceList = value;
                foreach (Variable var in sourceList)
                {
                    try
                    {
                        var.VariableChanged -= new EventHandler(var_VariableChanged);
                    }
                    catch(Exception e)
                    {
                        int k=0;
                    }
                }
                foreach (Variable var in sourceList)
                {
                    var.VariableChanged += new EventHandler(var_VariableChanged);
                }
            }
        }

        public ConditionSet Conditions
        {
            get { return conditionSet; }
            set 
            { 
                conditionSet = value; 
            }
        }                                   // Vanya edit end

        public SmartHouseEvent(string name, string description,List<Variable> list,ConditionSet set,bool isActive)
        {
            this.name = name;// problem: when create neccessary events from DB event is created twice
            this.description = description;
            sourceList = list;
            conditionSet = set;
            this.isActive = isActive;
            foreach (Variable var in list)
            {
                var.VariableChanged += new EventHandler(var_VariableChanged);
            }
        }

        void var_VariableChanged(object sender, EventArgs e)
        {
            if (conditionSet.CalcConditionSet()&&isActive)
            {
               // Logger.Instance().Record(((Variable)sender).Name + " : " + ((Variable)sender).CurrentValue.ToString());
                if (Triggered != null)
                    Triggered(this, new EventArgs());
            }
        }
    }
}
